package com.yic.module.device.service.deviceCategory;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yic.framework.common.enums.CommonStatusEnum;
import com.yic.module.device.enums.ErrorCodeConstants;
import com.yic.module.device.enums.deviceCategory.DeviceCategoryIdEnum;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.yic.module.device.controller.admin.deviceCategory.vo.*;
import com.yic.module.device.dal.dataobject.deviceCategory.DeviceCategoryDO;
import com.yic.framework.common.pojo.PageResult;

import com.yic.module.device.convert.deviceCategory.DeviceCategoryConvert;
import com.yic.module.device.dal.mysql.deviceCategory.DeviceCategoryMapper;

import static com.yic.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yic.framework.common.util.collection.CollectionUtils.convertSet;
import static com.yic.module.device.enums.ErrorCodeConstants.*;
import static com.yic.module.device.enums.ErrorCodeConstants.DEVICE_CATEGORY_CODE_DUPLICATE;

/**
 * 设备分类 Service 实现类
 *
 * @author 系统管理员
 */
@Service
@Validated
public class DeviceCategoryServiceImpl implements DeviceCategoryService {

    @Resource
    private DeviceCategoryMapper categoryMapper;

    @Override
    public Long createCategory(DeviceCategoryCreateReqVO createReqVO) {
        if (ObjectUtil.isEmpty(createReqVO.getParentId())){
            createReqVO.setParentId(DeviceCategoryIdEnum.ROOT.getId());
        }
        validateForCreateOrUpdate(null, createReqVO.getParentId(), createReqVO.getName(), createReqVO.getCode());
        // 插入
        DeviceCategoryDO category = DeviceCategoryConvert.INSTANCE.convert(createReqVO);
        categoryMapper.insert(category);
        // 返回
        return category.getId();
    }

    @Override
    public void updateCategory(DeviceCategoryUpdateReqVO updateReqVO) {
        if (ObjectUtil.isEmpty(updateReqVO.getParentId())){
            updateReqVO.setParentId(DeviceCategoryIdEnum.ROOT.getId());
        }
        // 校验
        validateForCreateOrUpdate(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName(), updateReqVO.getCode());
        // 更新
        DeviceCategoryDO updateObj = DeviceCategoryConvert.INSTANCE.convert(updateReqVO);
        categoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteCategory(Long id) {
        // 校验存在
        validateCategoryExists(id);
        // 校验是否有子分类
        validateDeviceCategoryChildExists(id);
        // TODO 校验当前分类下是否存在设备，若存在产品，则不允许删除
        // 删除
        categoryMapper.deleteById(id);
    }

    private void validateForCreateOrUpdate(Long id, Long parentId, String name, String code) {
        // 校验自己存在
        validateCategoryExists(id);
        // 校验分类名称唯一性
        validateDeviceCategoryNameUnique(id, parentId, name);
        // 校验分类代码唯一性
        validateDeviceCategoryCodeUnique(id, code);
        // 校验父部门的有效性
        validateParnetItemCategory(id, parentId);
    }

    private void validateCategoryExists(Long id) {
        if (id == null) {
            return;
        }
        if (categoryMapper.selectById(id) == null) {
            throw exception(DEVICE_CATEGORY_NOT_EXISTS);
        }
    }
    private void validateDeviceCategoryChildExists(Long id) {
        if (categoryMapper.selectChildCount(id) > 0) {
            throw exception(DEVICE_CATEGORY_EXITS_CHILDREN);
        }
    }

    @Override
    public DeviceCategoryDO getCategory(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public List<DeviceCategoryDO> getCategoryList(Collection<Long> ids) {
        return categoryMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<DeviceCategoryDO> getCategoryPage(DeviceCategoryPageReqVO pageReqVO) {
        return categoryMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DeviceCategoryDO> getCategoryList(DeviceCategoryExportReqVO exportReqVO) {
        return categoryMapper.selectList(exportReqVO);
    }

    @Override
    public List<DeviceCategoryDO> getDeviceCategoryList(DeviceCategoryReqVO reqVO) {
        return categoryMapper.selectList(reqVO);
    }

    private void validateParnetItemCategory(Long id, Long parentId) {
        // 顶级节点直接返回
        if (parentId == null || parentId.equals(DeviceCategoryIdEnum.ROOT.getId())){
            return;
        }
        // 检验自己是否为父级
        if (parentId.equals(id)){
            throw exception(DEVICE_CATEGORY_PARENT_ERROR);
        }
        // 校验父级是否存在
        DeviceCategoryDO deviceCategory = this.getDeviceCategory(parentId);
        if (ObjectUtil.isEmpty(deviceCategory)){
            throw exception(ErrorCodeConstants.DEVICE_CATEGORY_PARENT_NOT_EXITS);
        }
        // 校验父级分类状态
        if (CommonStatusEnum.DISABLE.equals(deviceCategory.getStatus())){
            throw exception(DEVICE_CATEGORY_NOT_ENABLE);
        }
        // TODO 父级不能为原来的子级
        List<DeviceCategoryDO> childItemCategoryList = this.getChildDeviceCategoryList(id);
        if (childItemCategoryList.stream().anyMatch(child -> child.getId().equals(parentId))) {
            throw exception(ITEM_CATEGORY_PARENT_IS_CHILD);
        }
    }

    private List<DeviceCategoryDO> getChildDeviceCategoryList(Long id) {
        List<DeviceCategoryDO> children = new LinkedList<>();
        // 遍历每一层
        Collection<Long> parentIds = Collections.singleton(id);
        for (int i = 0; i < Short.MAX_VALUE; i++) { // 使用 Short.MAX_VALUE 避免 bug 场景下，存在死循环
            // 查询当前层，所有的子部门
            List<DeviceCategoryDO> deviceCategoryDOS = categoryMapper.selectListByParentId(parentIds);
            // 1. 如果没有子部门，则结束遍历
            if (CollUtil.isEmpty(deviceCategoryDOS)) {
                break;
            }
            // 2. 如果有子部门，继续遍历
            children.addAll(deviceCategoryDOS);
            parentIds = convertSet(deviceCategoryDOS, DeviceCategoryDO::getId);
        }
        return children;
    }

    private DeviceCategoryDO getDeviceCategory(Long id) {
        return categoryMapper.selectById(id);
    }

    private void validateDeviceCategoryNameUnique(Long id, Long parentId, String name) {
        // 查询当前分类下是否有同名
        DeviceCategoryDO deviceCategoryDO = categoryMapper.selectByParentIdAndName(parentId, name);
        if (ObjectUtil.isEmpty(deviceCategoryDO)){
            return;
        }
        if (id == null){
            throw exception(DEVICE_CATEGORY_NAME_DUPLICATE);
        }
        if (!deviceCategoryDO.getId().equals(id)){
            throw exception(DEVICE_CATEGORY_NAME_DUPLICATE);
        }
    }

    private void validateDeviceCategoryCodeUnique(Long id, String code) {
        DeviceCategoryDO deviceCategoryDO = categoryMapper.selectByCode(code);
        if (ObjectUtil.isEmpty(deviceCategoryDO)){
            return;
        }
        if (id == null) {
            throw exception(DEVICE_CATEGORY_CODE_DUPLICATE);
        }
        if (!id.equals(deviceCategoryDO.getId())){
            throw exception(DEVICE_CATEGORY_CODE_DUPLICATE);
        }
    }

}
